package com.shigen.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shigen.shop.entity.User;
import com.shigen.shop.enums.BizCodeEnum;
import com.shigen.shop.exception.BizException;
import com.shigen.shop.mapper.UserMapper;
import com.shigen.shop.req.UserReq.LoginReq;
import com.shigen.shop.req.UserReq.RegisterReq;
import com.shigen.shop.service.UserService;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.stereotype.Service;

/**
 * @author shigenfu
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2022-07-24 14:30:10
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

  /**
   * 存储当前用户信息
   */
  public static ThreadLocal<User> threadLocal = new ThreadLocal<>();

  @Override
  public int register(RegisterReq register) {
    User user = new User();
    BeanUtil.copyProperties(register, user, true);

    String salt = RandomUtil.randomString(6);
    String cryptPwd = Md5Crypt.apr1Crypt(register.getPwd(), salt);
    user.setSecret(salt).setPwd(cryptPwd).setCreateTime(new Date());
    return getBaseMapper().insert(user);
  }

  @Override
  public User login(LoginReq loginReq) {
    String mail = loginReq.getMail();
    String pwd = loginReq.getPwd();
    if (StrUtil.isAllBlank(mail, pwd)) {
      throw new BizException(BizCodeEnum.ACCOUNT_FORMAT_ERROR);
    }
    User one = lambdaQuery().eq(User::getMail, mail).select(User::getSecret).one();
    log.info("one: {}", one);
    if (one == null) {
      throw new BizException(BizCodeEnum.ACCOUNT_PWD_ERROR);
    }
    User user = lambdaQuery().eq(User::getMail, mail).eq(User::getPwd, Md5Crypt.apr1Crypt(pwd, one.getSecret())).one();
    if (user != null) {
      threadLocal.set(user);
    } else {
      throw new BizException(BizCodeEnum.ACCOUNT_PWD_ERROR);
    }

    return user;
  }
}




